package site.timers.chat.util.netty;

import cn.hutool.core.date.LocalDateTimeUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.time.LocalDateTime;

/**
 * @Classname GroupChatServerHandler
 * @Description TODO
 * @Version 1.0.0
 * @Date 2025/8/12 14:47
 * @Author twl
 */
public class GroupChatServerHandler extends SimpleChannelInboundHandler<String> {

    /**
     * 定义一个channel组，管理所有的channel
     */
    private static final ChannelGroup CHANNEL_GROUP = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * 当建立连接时，第一个被执行
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        //通知其他客户，有人加入该聊天室
        CHANNEL_GROUP.writeAndFlush("【客户端】 " + LocalDateTimeUtil.formatNormal(LocalDateTime.now()) + channel.remoteAddress() + " 加入聊天 \n");
        //加入聊天
        CHANNEL_GROUP.add(channel);
    }


    /**
     * 表示channel处于一个活跃的状态
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("【" + ctx.channel().remoteAddress() + "】 " + LocalDateTimeUtil.formatNormal(LocalDateTime.now()) + " 上线了 ~");
    }

    /**
     *  表示channel处于不活动的状态
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("【" + ctx.channel().remoteAddress() + "】 " + LocalDateTimeUtil.formatNormal(LocalDateTime.now()) + " 离线了 ~");
    }


    /**
     * channel断开连接会被触发
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        CHANNEL_GROUP.writeAndFlush("【客户端】 " + LocalDateTimeUtil.formatNormal(LocalDateTime.now()) + channel.remoteAddress() + " 离开了 \n");
    }

    /**
     * 转发消息
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();
        CHANNEL_GROUP.forEach(ch -> {
            if (channel != ch) {
                ch.writeAndFlush("【客户】" + LocalDateTimeUtil.formatNormal(LocalDateTime.now()) + channel.remoteAddress() + "发送了消息: " + msg + "\n");
            } else {
                ch.writeAndFlush("【自己】" + LocalDateTimeUtil.formatNormal(LocalDateTime.now()) + "发送了消息: " + msg + "\n");
            }
        });
    }

    /**
     * 发生异常时 关闭通道
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
